package com.springboot.config.security.wx;

import com.springboot.entity.WxUser;
import com.springboot.enums.ErrorEnum;
import com.springboot.exception.MyException;
import com.springboot.repository.WxUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 *@author: lzh
 */
@Component
public class WxUserDetailsService implements UserDetailsService {

    @Autowired
    WxUserRepository wxUserRepository;

    @Override
    public UserDetails loadUserByUsername(String openid){
        WxUser wxUser = wxUserRepository.findByOpenid(openid);
        if(wxUser == null) {
            throw new MyException(ErrorEnum.WX_USER_LOGIN_MISS);
        } else if(wxUser.getIsLock()) {
            throw new MyException(ErrorEnum.WX_USER_LOCKED);
        }
        Set<GrantedAuthority> authoritiesSet = new HashSet();
        //添加微信用户权限
        authoritiesSet.add(new SimpleGrantedAuthority("ROLE_WXUSER"));
        if(wxUser.getIsProsecutor()) {
            //添加检查人员权限
            authoritiesSet.add(new SimpleGrantedAuthority("ROLE_PROSECUTOR"));
        }
        WxUserDetails wxUserDetails = new WxUserDetails();
        wxUserDetails.setAuthorities(authoritiesSet);
        wxUserDetails.setOpenid(openid);
        return wxUserDetails;
    }
}
